package lm.concurrency.day2.exercise;

import java.util.Random;

//@Slf4j
public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                a.transfer(b, randomAmount());
                //transfer(a,b,randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                b.transfer(a, randomAmount());
                //transfer(b,a,randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账2000次后的总金额
        System.out.println("a:"+a.getMoney());
        System.out.println("b:"+b.getMoney());
        System.out.println("total:"+(a.getMoney() + b.getMoney()));
        //log.debug("total:{}", (a.getMoney() + b.getMoney()));
    }

    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~100
    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }
//    public static synchronized void  transfer(Account A,Account B, int amount){
//        if (A.getMoney() >= amount) {
//            A.setMoney(A.getMoney() - amount);
//            B.setMoney(B.getMoney() + amount);
//        }
//    }
}

// 账户
class Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    // 转账
    public void transfer(Account target, int amount) {
        //synchronized (Account.class) {
            if (this.getMoney() >= amount) {
                this.setMoney(this.getMoney() - amount);
                target.setMoney(target.getMoney() + amount);
            }
        //}
    }
}
//测试脚本： for /L %n in (1,1,10) do java com.lm.experiment.concurrency.day2.exercise.ExerciseTransfer

